
# 对于购物车内商品的增删改查，用户与cart是 1 : 1 关系 ，当每次支付成功以后将购物车清空
import json


from django.http import HttpResponse

from entity.common.response import ResponseData, ResponseStatus
from orderApp.service.cartService import CartService
from utils.transfer import transferToJson


cartService = CartService()

def addGoods(request):
    if request.method == 'POST':
        user = json.loads(request.session['user'])
        print(request.body)
        goods = json.loads(request.body)
        cartService.addGoods(userId=user['id'],goodsId=goods['goodsId'],amount=goods['amount'])
    response = ResponseData(success=True,responseCode=ResponseStatus.COMPLETE_RESPONSE)
    return HttpResponse(content=transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)

def removeGoods(request):
    if request.method == 'POST':
        user = json.loads(request.session['user'])
        info = json.loads(request.body)
        cartService.removeGoods(userId=user['id'],cid=info['id'])
    response = ResponseData(success=True,responseCode=ResponseStatus.COMPLETE_RESPONSE)
    return HttpResponse(content=transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)

# 数量改变
def changeAmount(request):
    if request.method == 'POST':
        user = json.loads(request.session['user'])
        goods = json.load(request.body)
        cartService.update(userId=user['id'],goods=goods)
    response = ResponseData(success=True,responseCode=ResponseStatus.COMPLETE_RESPONSE)
    return HttpResponse(content=transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)

def clearShoppingCart(request):
    user = json.loads(request.session['user'])
    cartService.clearGoods(userId=user['id'])
    response = ResponseData(success=True, responseCode=ResponseStatus.COMPLETE_RESPONSE)
    return HttpResponse(content=transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)

def getAllGoods(request):
    user = json.loads(request.session['user'])
    data = cartService.getByUserId(userId=user['id'])
    response = ResponseData(success=True, responseCode=ResponseStatus.COMPLETE_RESPONSE,data=data)
    return HttpResponse(content=transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)

